// 初始化 PDF.js
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

async function loadPDF(file, canvasId, pdfNum) {
    try {
        const arrayBuffer = await file.arrayBuffer();
        const pdf = await pdfjsLib.getDocument(arrayBuffer).promise;
        
        if (pdfNum === 1) {
            pdf1 = pdf;
            currentPage1 = 1;
        } else {
            pdf2 = pdf;
            currentPage2 = 1;
        }

        log(`PDF ${pdfNum} 加载成功，共 ${pdf.numPages} 页`);
        await renderPage(pdfNum);
        
        if (pdf1 && pdf2) {
            comparePages();
        }
    } catch (error) {
        log(`PDF ${pdfNum} 加载失败: ${error.message}`);
    }
}

async function renderPage(pdfNum) {
    const canvas = pdfNum === 1 ? canvas1 : canvas2;
    const ctx = pdfNum === 1 ? ctx1 : ctx2;
    const pdf = pdfNum === 1 ? pdf1 : pdf2;
    const pageNum = pdfNum === 1 ? currentPage1 : currentPage2;
    const pageSpan = document.getElementById(`page${pdfNum}`);

    try {
        const page = await pdf.getPage(pageNum);
        const viewport = page.getViewport({ scale: 1.5 });
        
        canvas.width = viewport.width;
        canvas.height = viewport.height;

        await page.render({
            canvasContext: ctx,
            viewport: viewport
        }).promise;

        pageSpan.textContent = `第 ${pageNum} 页 / 共 ${pdf.numPages} 页`;
        
        if (pdf1 && pdf2) {
            comparePages();
        }
    } catch (error) {
        log(`页面渲染失败: ${error.message}`);
    }
}

async function changePage(pdfNum, delta) {
    if (pdfNum === 1 && pdf1) {
        currentPage1 = Math.max(1, Math.min(currentPage1 + delta, pdf1.numPages));
        await renderPage(1);
    } else if (pdfNum === 2 && pdf2) {
        currentPage2 = Math.max(1, Math.min(currentPage2 + delta, pdf2.numPages));
        await renderPage(2);
    }
} 